package com.szrt.javaweb.department.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;
import com.szrt.javaweb.department.entity.DepartmentEntity;
import com.szrt.javaweb.department.service.DepartmentService;
import com.szrt.javaweb.department.service.impl.DepartmentServiceImpl;

public class DepartmentController extends HttpServlet {
	
	
	private DepartmentService service = new DepartmentServiceImpl();
	
	private static final long serialVersionUID = 3594278266578582494L;
	
	
	
	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) 
			throws ServletException, IOException {
		
		// /department.do?method=list    ==>  /department/list.do
		
		String method = req.getParameter("method");
		
		if("list".equals(method)){
			
			list(req,resp);
		}
		
	}

	private void list(HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, IOException{
		
		//1 从数据库中查询到所有的部门的列表List<DepartmentEntity> list
		List<DepartmentEntity> departmentList = service.findAll();
		
		
		//2 把List<DepartmentEntity> list变成json格式的字符串。   ==>json 前后台 交互数据
		
		Gson json = new Gson();
		String jsonDepartmentList=json.toJson(departmentList);
		
		
		//3把json格式的字符串直接写到页面  以下的步骤是固定不变 死的代码
		printJsonToPage(response, jsonDepartmentList);
		
		
		
	}

	
	/**
	 * 把JSON格式的字符串输出到页面    在页面上可以拿到你json格式的部门列表
	 * @param response
	 * @param jsonDepartmentList
	 * @throws IOException
	 */
	private void printJsonToPage(HttpServletResponse response, String jsonDepartmentList) throws IOException {
		//3.1 设置格式utf-8避免页面乱码
		response.setContentType("text/html;charset=utf-8"); //防止ajax乱码...
		
		//后台从来不负责跳转。 后台值负责给数据
		//3.2 得到打印流 并且把这个流写到页面
		PrintWriter out = response.getWriter();
		
		//3.3 可以把 jsonDepartmentList 写入到页面
		out.write(jsonDepartmentList);
		
		
		//3.4 关闭流
		out.flush();
		out.close();
	}

}
